package com.blb.day3;

import java.util.ArrayList;
import java.util.List;

/**
 * 包子店
 */
public class BaoziShop {

    //仓库上限
    public static final int MAX_COUNT = 100;
    //包子仓库
    private List<Baozi> baozis = new ArrayList<>();

    //做包子
    public synchronized void makeBaozi(){
        //如果仓库满，就让当前线程等待
        if(baozis.size() == MAX_COUNT){
            System.out.println("仓库满了，生产线程等待!"+Thread.currentThread().getName());
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            //如果没有满，通知生产者继续生产
            this.notifyAll();
        }
        if(baozis.size() < MAX_COUNT) {
            //创建包子
            Baozi baozi = new Baozi(baozis.size());
            baozis.add(baozi);
            System.out.println("生产者"+Thread.currentThread().getName()+"做了"+baozi);
        }
    }

    //卖包子
    public synchronized void sellBaozi(){
        //如果仓库空了，让消费者线程等待
        if(baozis.size() == 0){
            System.out.println("仓库空了，消费线程等待!"+Thread.currentThread().getName());
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            //如果没空，通知消费者消费
            this.notifyAll();
        }
        if(baozis.size() != 0){
            //消费包子
            Baozi baozi = baozis.remove(baozis.size() - 1);
            System.out.println("消费者"+Thread.currentThread().getName()+"吃了"+baozi);
        }
    }

}
